package com.zhongxi.guoyuan.view.seller;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.TextureView;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RatingBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.util.LogTime;
import com.google.gson.Gson;
import com.libs.zxing.CaptureActivity;
import com.weigan.loopview.LoopView;
import com.weigan.loopview.OnItemSelectedListener;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.Permission;
import com.yanzhenjie.permission.PermissionListener;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.seller.SellerExchangeAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.EventBusMessage;
import com.zhongxi.guoyuan.entity.seller.EarningsInfo;
import com.zhongxi.guoyuan.entity.seller.ExpressCompany;
import com.zhongxi.guoyuan.entity.seller.InnerMallResult;
import com.zhongxi.guoyuan.entity.seller.OrderInfoDdBean;
import com.zhongxi.guoyuan.entity.seller.SellerMallOrderResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.ImageUtils;
import com.zhongxi.guoyuan.utils.ToastUtil;
import com.zhongxi.guoyuan.utils.UiUtils;
import com.zhongxi.guoyuan.widget.view.MyScrollView;
import com.zhongxi.guoyuan.widget.xlistview.XListView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class SellerExchangeBeanActivity extends BaseActivity implements MyScrollView.OnScrollListener {


    @Bind(R.id.title)
    RelativeLayout title;
    @Bind(R.id.ivBack)
    ImageView ivBack;
    @Bind(R.id.tvTitle)
    TextView tvTitle;
    @Bind(R.id.btn_verify)
    Button btnVerify;
    @Bind(R.id.seller_exchange_scrollview)
    MyScrollView scrollView;
    @Bind(R.id.relaLayout)
    LinearLayout relaLayout;
    @Bind(R.id.seller_exchange_name)
    TextView sellerExchangeName;
    @Bind(R.id.seller_exchange_apply)
    TextView sellerExchangeApply;
    @Bind(R.id.seller_exchange_id)
    TextView sellerExchangeId;
    @Bind(R.id.ratingBar)
    RatingBar ratingBar;
    @Bind(R.id.seller_md)
    TextView sellerMd;
    @Bind(R.id.seller_hd)
    TextView sellerHd;
    @Bind(R.id.seller_exchange_total)
    TextView sellerExchangeTotal;
    @Bind(R.id.seller_ordernum)
    TextView sellerOrdernum;
    @Bind(R.id.post_value)
    TextView postValue;
    @Bind(R.id.seller_exchange_startTime)
    TextView sellerExchangeStartTime;
    @Bind(R.id.seller_exchange_endTime)
    TextView sellerExchangeEndTime;
    @Bind(R.id.seller_exchange_md)
    TextView sellerExchangeMd;
    @Bind(R.id.seller_exchange_Hd)
    TextView sellerExchangeHd;
    @Bind(R.id.seller_exchange_searchordernum)
    TextView sellerExchangeSearchordernum;
    @Bind(R.id.seller_change_ordernum)
    TextView sellerChangeOrdernum;
    @Bind(R.id.post_change_value)
    TextView postChangeValue;
    @Bind(R.id.linearBegin)
    LinearLayout linearBegin;
    @Bind(R.id.scrollBody)
    LinearLayout scrollBody;
    @Bind(R.id.rb0)
    RadioButton rb0;
    @Bind(R.id.rb1)
    RadioButton rb1;
    @Bind(R.id.rb2)
    RadioButton rb2;
    @Bind(R.id.rb3)
    RadioButton rb3;
    @Bind(R.id.rb4)
    RadioButton rb4;
    @Bind(R.id.lvList)
    XListView mXListView;
    @Bind(R.id.linearStop)
    LinearLayout linearStop;
    @Bind(R.id.rl_period)
    RelativeLayout rl_period;

    private String type;

    @Bind(R.id.et_search)
    EditText etSearch;
    @Bind(R.id.et_clear)
    TextView etClear;
    @Bind(R.id.et_hint_text)
    TextView etHintText;
    @Bind(R.id.et_text_cancel)
    TextView etTextCancel;
    @Bind(R.id.iv_search)
    ImageView ivSearch;

    private static final int SELLERPAYMONEY = 00;
    private static final String TAG = "SellerExchangeBeanActiv";  //EE792E6AE8

    private InnerMallResult.ConsoleBean consoleBean;
    private DatePickerDialog dialog;
    private String startTime;
    private String endTime;
    private Map<String, String> map;
    private String userphone = "";
    private SellerExchangeAdapter adapter;
    private List<OrderInfoDdBean> list = new ArrayList<>();
    private String dateNowStr;
    private boolean isMeasure;
    private int mMeasuredHeight;
    private int mOrdertype = 1;
    private static final long TIME = 200;
    private int pos;
    private int flag = 0;
    Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            pos = msg.getData().getInt("pos");
            switch (msg.what) {
                case 1:
                    flag = msg.getData().getInt("flag", 0);
                    map.clear();
                    map.put("orderid", msg.getData().getString("orderid"));
                    map.put("shopid", msg.getData().getString("shopid"));
                    type = "prepareGoods";
                    getServer(Url.EXCHANGESTOCKUP, map, "", true, null, "post");
                    break;
                case 2:
                    sendExpressage(msg.getData().getString("orderid"));
                    break;
                case 3:
                    map.clear();
                    map.put("orderid", msg.getData().getString("orderid"));
                    type = "over";
                    getServer(Url.EXCHANGEFIXCOMPLAINTS, map, "", true, null, "post");
                    break;
            }
        }
    };
    private String expressNum;
    private AlertDialog alertDialog;

    private void sendExpressage(final String orderid) {
        try {
            final List<String> spList = new ArrayList<String>();
            final List<ExpressCompany> expressCompanies = new ArrayList<>();
            JSONObject express = new JSONObject(MyApplication.getInstance().getLogistics());
            Iterator<String> iterator = express.keys();
            while (iterator.hasNext()) {
                ExpressCompany expressCompany = new ExpressCompany();
                String key = iterator.next();
                String value = express.optString(key);
                expressCompany.setExpressNum(key);
                expressCompany.setExpressName(value);
                spList.add(value);
                expressCompanies.add(expressCompany);
            }
            AlertDialog.Builder adb = new AlertDialog.Builder(context);
            final AlertDialog dialog1 = adb.create();
            View view = View.inflate(context, R.layout.dialog_post_silver_send_good, null);
            ImageView ivCancel = (ImageView) view.findViewById(R.id.ivCancel);
            LoopView loopView = (LoopView) view.findViewById(R.id.loopView);
            loopView.setInitPosition(0);
            loopView.setNotLoop();
            loopView.setListener(new OnItemSelectedListener() {
                @Override
                public void onItemSelected(int index) {
                    String s = spList.get(index);
                    for (ExpressCompany ec : expressCompanies) {
                        if (s.equals(ec.getExpressName())) {
                            expressNum = ec.getExpressNum();
                        }
                    }
                }
            });
            loopView.setItems(spList);
            final EditText et_expressNumber = (EditText) view.findViewById(R.id.et_expressNumber);
            TextView btSubmit = (TextView) view.findViewById(R.id.btSubmit);
            btSubmit.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    String trim = et_expressNumber.getText().toString().trim();
                    if (TextUtils.isEmpty(expressNum)) {
                        showShortToast("快递公司不能为空");
                    } else if (TextUtils.isEmpty(trim)) {
                        showShortToast("快递单号不能为空");
                    } else {
                        dialog1.dismiss();
                        map.clear();
                        map.put("orderid", orderid);
                        map.put("shippercode", expressNum);
                        map.put("logisticscode", trim);
                        type = "sendExpress";
                        getServer(Url.EXCHANGEDELIVERGOODS, map, "", true, null, "post");
                    }
                }
            });

            ivCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog1.dismiss();
                }
            });

            dialog1.setView(view);
            dialog1.show();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private boolean isLoadMore;
    private boolean issearch;

    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_seller_exchangebean);
        ButterKnife.bind(this);
        tvTitle.setText("豆豆兑换供货商");
        mXListView.setPullRefreshEnable(false);
        mXListView.setPullLoadEnable(true);
        relaLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (!isMeasure) {
                    mMeasuredHeight = relaLayout.getMeasuredHeight();
                    isMeasure = true;
                }
                return true;
            }
        });
        EventBus.getDefault().register(this);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new SellerExchangeAdapter(this, list, mHandler);
        mXListView.setAdapter(adapter);
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        dateNowStr = sdf.format(now);
        sellerExchangeStartTime.setText(dateNowStr);
        sellerExchangeEndTime.setText(dateNowStr);
        startTime = endTime = dateNowStr;
        getData();
    }

    /***
     * 汇总统计
     */
    private void getData() {
        type = "total";
        getServer(Url.BUSINESSCENTER_INNERMALL, null, "", true, null, "get");
    }

    /***
     * 时间段内汇总统计
     */
    private void getQueryInfo() {
        map = new HashMap<>();
        if (CommonTool.TimeCompare(startTime, endTime)) {
            type = "queryInfo";
            map.clear();
            map.put("stime", startTime);
            map.put("etime", endTime);
            getServer(Url.BUSINESSCENTER_INNERMALL_BYTIME, map, "", true, null, "post");
        } else {
            showShortToast("结束时间不能小于开始时间");
        }
    }

    private void getOrderList() {
        type = "order";
        String str = "&page=" + pageNum + "&userphone=" + userphone + "&ordertype=" + mOrdertype;
        getServer(Url.BUSINESSCENTER_ORDERLIST, null, str, true, null, "get");
    }


    @Override
    protected void initEvent() {
        super.initEvent();
        scrollView.setOnScrollListener(this);
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                if (charSequence.length() > 0) {
                    etClear.setVisibility(View.VISIBLE);
                    etTextCancel.setVisibility(View.VISIBLE);
                    etTextCancel.setText("搜索");
                } else {
                    etTextCancel.setVisibility(View.VISIBLE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setText("取消");
                }
                etHintText.setVisibility(View.GONE);
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        mXListView.setXListViewListener(new XListView.IXListViewListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                pageNum = 1;
                userphone = etSearch.getText().toString().trim();
                getOrderList();
            }

            @Override
            public void onLoadMore() {
                isLoadMore = true;
                pageNum++;
                userphone = etSearch.getText().toString().trim();
                getOrderList();
            }
        });
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        if (type.equals("total")) {
            InnerMallResult result = gson.fromJson(response, InnerMallResult.class);
            MyApplication.getInstance().setSpValue(result.safeobj);
            initInfo(result);
            getQueryInfo();
        } else if (type.equals("queryInfo")) {
            InnerMallResult result = gson.fromJson(response, InnerMallResult.class);
            MyApplication.getInstance().setSpValue(result.safeobj);
            initQuery(result);
            getOrderList();
        } else if (type.equals("order")) {
            try {
                SellerMallOrderResult result = gson.fromJson(response, SellerMallOrderResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if (isLoadMore) {
                    isLoadMore = false;
                    if (result.getOrderInfo() == null || result.getOrderInfo().size() == 0) {
                        showShortToast("没有加载更多了");
                        isFinish();
                        pageNum--;
                        return;
                    }
                }
                if (pageNum == 1) {
                    list.clear();
                }
                JSONObject mObject = new JSONObject(response);
                if (result.getOrderInfo() != null && result.getOrderInfo().size() > 0) {
                    JSONObject mOrderCus = mObject.optJSONObject("orderCus");
                    JSONObject mUser = mObject.optJSONObject("user");
                    JSONObject mComplaints = mObject.optJSONObject("complaints");
                    List<OrderInfoDdBean> mOrderInfo = result.getOrderInfo();
                    for (int i = 0; i < mOrderInfo.size(); i++) {
                        OrderInfoDdBean mOrderInfoDdBean = mOrderInfo.get(i);
                        String mId = mOrderInfoDdBean.getId();
                        if (null != mOrderCus && mOrderCus.length() > 0) {
                            JSONObject mObjectOrderCus = mOrderCus.optJSONObject(mId);
                            if (null != mObjectOrderCus && !"".equals(mObjectOrderCus)) {
                                mOrderInfoDdBean.setShippercode(mObjectOrderCus.optString("shippercode"));
                                mOrderInfoDdBean.setLogisticscode(mObjectOrderCus.optString("logisticscode"));
                                mOrderInfoDdBean.setConsignee(mObjectOrderCus.optString("consignee"));
                                mOrderInfoDdBean.setConsigneemphone(mObjectOrderCus.optString("consigneemphone"));
                                mOrderInfoDdBean.setShippingaddress(mObjectOrderCus.optString("shippingaddress"));
                                mOrderInfoDdBean.setDeliveredtime(mObjectOrderCus.optString("deliveredtime"));
                                mOrderInfoDdBean.setReceivetime(mObjectOrderCus.optString("receivetime"));
                            }
                        }
                        if (null != mUser && !"".equals(mUser)) {
                            mOrderInfoDdBean.setUserPhone(mUser.optString(mOrderInfoDdBean.getUserid()));
                        }
                        if (null != mComplaints && !"".equals(mComplaints)) {
                            mOrderInfoDdBean.setComplain(mComplaints.optString(mId));
                        }
                    }
                    list.addAll(mOrderInfo);
                    adapter.setOrderType(mOrdertype);
                } else {
                    if (pageNum > 1) {
                        pageNum--;
                        isFinish();
                    } else {
                        ToastUtil.show("暂无数据");
                    }
                    if (issearch && !TextUtils.isEmpty(userphone)) {
                        ToastUtil.show("没有该手机号对应的商品");
                    }
                }
                adapter.notifyDataSetChanged();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else if ("prepareGoods".equals(type)) {
            BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
            if (1 == mOrdertype) {
                list.get(pos).setOrderstatus(1);
            } else {
                list.get(pos).setPoststatus(1);
            }
            adapter.notifyDataSetChanged();
        } else if ("sendExpress".equals(type)) {
            BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
            showShortToast("快递发货成功");
            list.remove(pos);
            adapter.notifyDataSetChanged();
        } else if ("over".equals(type)) {
            BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
            MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
            showShortToast("投诉订单已解决完成");
            list.remove(pos);
            adapter.notifyDataSetChanged();
        }
    }

    private void isFinish() {
        mXListView.stopRefresh();
        mXListView.stopLoadMore();
        mXListView.setRefreshTime("刚刚");
    }

    private void initQuery(InnerMallResult result) {
        if (null != result && !"".equals(result)) {
            if (null != result.earningsInfo && !"".equals(result.earningsInfo)) {
                EarningsInfo mEarningsInfo = result.earningsInfo;
                sellerExchangeMd.setText(mEarningsInfo.getInnerprice());
                sellerExchangeHd.setText(mEarningsInfo.getRedbean());
                sellerExchangeSearchordernum.setText(mEarningsInfo.getPrice());
                sellerChangeOrdernum.setText("下单量:  " + mEarningsInfo.getOrdernum() + " 单");
                postChangeValue.setText(mEarningsInfo.getPostage() + " 红豆");
            }
        }
    }

    private void initInfo(InnerMallResult result) {
        if (null != result && !"".equals(result)) {
            if (null != result.data && !"".equals(result.data)) {
                consoleBean = result.data;
                sellerExchangeName.setText(consoleBean.name);
                //商家标识
                sellerExchangeId.setText("ID：" + consoleBean.id);
                ratingBar.setRating(consoleBean.starlevel);
            }
            if (null != result.earningsInfo && !"".equals(result.earningsInfo)) {
                EarningsInfo mInfo = result.earningsInfo;
                sellerMd.setText(mInfo.getInnerprice());
                sellerHd.setText(mInfo.getRedbean());
                sellerExchangeTotal.setText(mInfo.getPrice());
                sellerOrdernum.setText("下单量:  " + mInfo.getOrdernum() + " 单");
                postValue.setText(mInfo.getPostage() + " 红豆");
            }
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        BaseResponse baseResponse = gson.fromJson(response, BaseResponse.class);
        MyApplication.getInstance().setSpValue(baseResponse.getSafeobj());
        if (baseResponse.getCode() == 9002) {
            ToastUtil.show("登录已失效，请重新登录");
            MyApplication.getInstance().sharedPrefrences.edit().putString("MDChangecredentials", "").commit();
            finish();
        } else if (baseResponse.getCode() == 9003) {
            ToastUtil.show("该店铺已关闭");
            MyApplication.getInstance().sharedPrefrences.edit().putString("MDChangecredentials", "").commit();
            finish();
        } else if (baseResponse.getCode() == 2016) {
            ToastUtil.show("订单定制信息已丢失");
        }
    }

    private Runnable runnable = new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(MyScrollView.FOCUS_UP);
        }
    };

    @OnClick({R.id.ivBack, R.id.btn_verify, R.id.seller_exchange_apply, R.id.seller_exchange_startTime, R.id.seller_exchange_endTime,
            R.id.et_clear, R.id.et_search, R.id.et_text_cancel, R.id.iv_search, R.id.rb0, R.id.rb1, R.id.rb2, R.id.rb3, R.id.rb4})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ivBack:
                onBackPressed();
                break;
            case R.id.btn_verify:  //自提验证
                showVerifyPopupwindow();
                break;
            case R.id.seller_exchange_apply://美豆兑换，申请提现
//                startAct(SellerMallExchangeActivity.class);
                int mVisibility = rl_period.getVisibility();
                if (0 == mVisibility) {   // 显示
                    rl_period.setVisibility(View.GONE);
                } else {
                    rl_period.setVisibility(View.VISIBLE);
                }
                relaLayout.getViewTreeObserver().addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
                    @Override
                    public boolean onPreDraw() {
                        mMeasuredHeight = relaLayout.getMeasuredHeight();
                        return true;
                    }
                });
                break;
            case R.id.seller_exchange_startTime:
                showDateDialog(0);
                break;
            case R.id.seller_exchange_endTime:
                showDateDialog(1);
                break;
            case R.id.iv_search:
                pageNum = 1;
                userphone = etSearch.getText().toString().trim();
                if (!TextUtils.isEmpty(userphone)) {
                    issearch = true;
                    getOrderList();
                } else {
                    ToastUtil.show("请输入正确的手机号");
                }
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_text_cancel:
                userphone = etSearch.getText().toString().trim();
                if (userphone.length() > 0) {
                    pageNum = 1;
                    if (!TextUtils.isEmpty(userphone)) {
                        issearch = true;
                        getOrderList();
                    } else {
                        ToastUtil.show("请输入正确的手机号");
                    }
                } else {
                    etSearch.setText("");
                    etHintText.setVisibility(View.VISIBLE);
                    etClear.setVisibility(View.GONE);
                    etTextCancel.setVisibility(View.GONE);
                    getOrderList();
                }
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_clear:
                etSearch.setText("");
                etHintText.setVisibility(View.VISIBLE);
                etTextCancel.setText("取消");
                etTextCancel.setVisibility(View.VISIBLE);
                CommonTool.hideSoft(etSearch, context);
                break;
            case R.id.et_search:
                etTextCancel.setVisibility(View.VISIBLE);
                break;
            case R.id.rb0:
                mOrdertype = 1;
                pageNum = 1;
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    mHandler.postDelayed(runnable, TIME);
                }
                rb0.setChecked(true);
                rb1.setChecked(false);
                rb2.setChecked(false);
                rb3.setChecked(false);
                rb4.setChecked(false);
                getOrderList();
                break;
            case R.id.rb1:
                mOrdertype = 2;
                pageNum = 1;
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    mHandler.postDelayed(runnable, TIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(true);
                rb2.setChecked(false);
                rb3.setChecked(false);
                rb4.setChecked(false);
                getOrderList();
                break;
            case R.id.rb2:
                mOrdertype = 3;
                pageNum = 1;
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    mHandler.postDelayed(runnable, TIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(false);
                rb2.setChecked(true);
                rb3.setChecked(false);
                rb4.setChecked(false);
                getOrderList();
                break;
            case R.id.rb3:
                mOrdertype = 4;
                pageNum = 1;
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    mHandler.postDelayed(runnable, TIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(false);
                rb2.setChecked(false);
                rb3.setChecked(true);
                rb4.setChecked(false);
                getOrderList();
                break;
            case R.id.rb4:
                mOrdertype = 5;
                pageNum = 1;
                if (scrollBody.getParent() != linearBegin) {
                    linearStop.removeView(scrollBody);
                    linearBegin.addView(scrollBody);
                    mHandler.postDelayed(runnable, TIME);
                }
                rb0.setChecked(false);
                rb1.setChecked(false);
                rb2.setChecked(false);
                rb3.setChecked(false);
                rb4.setChecked(true);
                getOrderList();
                break;
        }
    }

    private void showDateDialog(final int index) {
        Calendar c = Calendar.getInstance();
        dialog = new DatePickerDialog(this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                String mon = month + 1 + "";
                String text = year + "-" + mon + "-" + dayOfMonth;

                text = CommonTool.TimeCompare(text, dateNowStr) ? text : dateNowStr;
                if (index == 0) {
                    sellerExchangeStartTime.setText(text);
                    startTime = text;
                } else if (index == 1) {
                    sellerExchangeEndTime.setText(text);
                    endTime = text;
                }
                pageNum = 1;
                getQueryInfo();
            }
        }, c.get(Calendar.YEAR), c.get(Calendar.MONTH), c.get(Calendar.DAY_OF_MONTH));
        dialog.setTitle("请选择时间：");
        dialog.getDatePicker().setCalendarViewShown(false);
        dialog.show();
    }

    private void showVerifyPopupwindow() {
        View view = View.inflate(context, R.layout.pop_verify, null);
        final PopupWindow pop = new PopupWindow(view, LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, true);
        LinearLayout rl_message = (LinearLayout) view.findViewById(R.id.rl_message);
        LinearLayout rl_dialogue = (LinearLayout) view.findViewById(R.id.rl_dialogue);
        rl_message.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
                showVerifyDialog();
            }
        });
        rl_dialogue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                pop.dismiss();
//                startAct(PayMoneyActivity.class);
                AndPermission.with(context)
                        .requestCode(100)
                        .permission(Permission.CAMERA)
                        .callback(new PermissionListener() {
                            @Override
                            public void onSucceed(int requestCode, @NonNull List<String> grantPermissions) {
                                //跳到扫描二维码页面
                                Intent payIntent = new Intent(context, CaptureActivity.class);
                                //跳液面需要返回一个结果
                                startActivityForResult(payIntent, SELLERPAYMONEY);
                            }

                            @Override
                            public void onFailed(int requestCode, @NonNull List<String> deniedPermissions) {

                            }
                        })
                        .start();
            }
        });
        pop.setBackgroundDrawable(new BitmapDrawable());
        pop.setFocusable(true);
        int screenWidth = ImageUtils.getScreenWidth(context);
        view.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int viewMeasuredWidth = view.getMeasuredWidth();
        title.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int titleMeasuredHeight = title.getMeasuredHeight();
        btnVerify.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int iv_verifyMeasuredHeight = btnVerify.getMeasuredHeight();
        pop.showAtLocation(btnVerify, Gravity.TOP | Gravity.START, screenWidth - viewMeasuredWidth, titleMeasuredHeight + (iv_verifyMeasuredHeight / 2));
    }

    private void showVerifyDialog() {
        AlertDialog.Builder adb = new AlertDialog.Builder(context);
        alertDialog = adb.create();
        View dialogView = View.inflate(context, R.layout.dialog_verify, null);
        ImageView iv_dimess = (ImageView) dialogView.findViewById(R.id.iv_dimess);
        final EditText et_verifyId = (EditText) dialogView.findViewById(R.id.et_verifyId);
        TextView btSubmit = (TextView) dialogView.findViewById(R.id.btSubmit);
        iv_dimess.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                alertDialog.dismiss();
            }
        });
        btSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_verifyId.getText().toString().trim();
                if (TextUtils.isEmpty(trim)) {
                    showShortToast("请输入您正确的提货验证码");
                } else {
                    Intent intent = new Intent(context, SellerVerifyDdActivity.class);
                    intent.putExtra("trim", trim);
                    startActivity(intent);
                }
            }
        });
        alertDialog.setView(dialogView);
        alertDialog.show();
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= mMeasuredHeight) {
            if (scrollBody.getParent() != linearStop) {
                linearBegin.removeView(scrollBody);
                linearStop.addView(scrollBody);
            }
        } else {
            if (scrollBody.getParent() != linearBegin) {
                linearStop.removeView(scrollBody);
                linearBegin.addView(scrollBody);
            }
        }
    }


    @Override
    public void scrollBottom() {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == SELLERPAYMONEY) {
            //获取解析的数据
            String text = data.getStringExtra("text");
            Intent intent = new Intent(context, SellerVerifyDdActivity.class);
            intent.putExtra("text", text);
            startActivity(intent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void eventMessage(EventBusMessage message) {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
        for (int i = 0; i < list.size(); i++) {
            if (message.getOrderid().equals(list.get(i).getId())) {
                list.get(i).setOrderstatus(2);
            }
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
